import email
import random
import string

from django.contrib.auth import login, logout
from django.contrib.auth.decorators import login_required
from django.core.mail import send_mail
from django.db.models import Q
from django.http import JsonResponse, HttpResponse
from django.shortcuts import render, redirect, reverse
from django.views.decorators.http import require_http_methods, require_POST, require_GET

from api.forms import StudentSignUpForm
from api.models import *


# Create your views here.

@require_GET
def index(request):
    course_teachs = CourseTeacher.objects.all()
    return render(request, 'index.html', {'course_teachs': course_teachs})


# 学生登录
@require_http_methods(['GET', 'POST'])
def stu_login(request):
    if request.method == 'POST':
        email = request.POST.get('email')
        password = request.POST.get('password')
        user = CustomUser.objects.filter(email=email).first()
        if user and user.check_password(password):
            login(request, user)
            return redirect(reverse('api:index'))
        else:
            return HttpResponse("用户名或密码错误")
    else:
        return render(request, 'student_login.html')


# 老师登录
@require_http_methods(['GET', 'POST'])
def tea_login(request):
    if request.method == 'POST':
        phone = request.POST.get('phone')
        password = request.POST.get('password')
        if phone == '' or password == '':
            return render(request, 'teacher_login.html', {'error': '用户名或密码不能为空'})
        # 查找 TeacherProfile
        teacher_profile = TeacherProfile.objects.filter(phone=phone).first()
        if teacher_profile:
            user = teacher_profile.user
            if user.check_password(password):
                login(request, user)
                return redirect('/')
            else:
                return render(request, 'teacher_login.html', {'error': '用户名或密码错误'})
        else:
            return render(request, 'teacher_login.html', {'error': '用户名或密码错误'})
    else:
        return render(request, 'teacher_login.html')


# 老师注册
@require_http_methods(['GET', 'POST'])
def ted_register(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        phone = request.POST.get('phone')
        position = request.POST.get('position')
        invited = request.POST.get('invited')
        password = request.POST.get('password')
        if not username and phone and position and password:
            return HttpResponse("信息填写不完整")
        # 校验邀请码
        if not InviteCodeModel.objects.filter(code=invited, used=False).exists():
            return HttpResponse("邀请码错误")
        if TeacherProfile.objects.filter(phone=phone).exists():
            return HttpResponse("用户已存在")
        try:
            # 邀请码正确，用户唯一
            InviteCodeModel.objects.filter(code=invited, used=False).update(used=True)
            user = CustomUser.objects.create_user(username=username, password=password, is_teacher=True)
            TeacherProfile.objects.create(user=user, phone=phone, profession=position)
            return redirect(reverse('api:tea_login'))
        except Exception as e:
            print(e)
            return HttpResponse("注册失败")
    else:
        return render(request, 'tea_register.html')


# 学生注册
@require_http_methods(['GET', 'POST'])
def student_register(request):
    if request.method == 'POST':
        print("开始校验用户")
        print(request.POST)
        email = request.POST.get('email')
        username = request.POST.get('username')
        captcha = request.POST.get('captcha')
        password = request.POST.get('password')
        if not CaptchaModel.objects.filter(email=email, captcha=captcha).exists():
            print("验证码正确")
            return HttpResponse("验证码错误")
        if CustomUser.objects.filter(email=email).exists():
            print("用户已存在")
            return HttpResponse("用户已存在")
        if CustomUser.objects.filter(username=username).exists():
            print("用户名已存在")
            return HttpResponse("用户名已存在")
        else:
            user = CustomUser.objects.create_user(email=email, username=username, password=password, is_student=True)
            StudentProfile.objects.create(user=user)
            CaptchaModel.objects.filter(email=email, captcha=captcha).delete()
            return redirect(reverse('api:stu_login'))

    else:
        return render(request, 'student_register.html')


# 发送邮箱验证码
def sen_email_captcha(request):
    email = request.GET.get('email')
    print("获取到的email是", email)
    if not email:
        return JsonResponse({'code': 400, 'msg': '邮箱不能为空'})

    # 生成验证码
    captcha = ''.join(random.sample(string.digits, 6))
    # 存储验证码到数据库
    CaptchaModel.objects.update_or_create(email=email, defaults={'captcha': captcha})  # 没有则新建
    # 发送邮件
    send_mail("注册验证码", message=f"您的注册验证码是{captcha}", recipient_list=[email],
              from_email=None)
    return JsonResponse({'code': 200, 'msg': '邮箱验证码发送成功'})


# 学生修改信息
@login_required
@require_http_methods(['GET', 'POST'])
def stu_change(request):
    if request.method == 'POST':
        print("开始校验用户")
        print(request.POST)
        email = request.POST.get('email')
        password = request.POST.get('password')

        user = CustomUser.objects.filter(email=email).first()
        if user:
            # 密码校验通过，可以修改密码
            user.set_password(password)
            user.save()
            return HttpResponse("密码更新成功")
        else:
            return HttpResponse("修改失败！")
    else:
        return render(request, 'stu_change.html')


# 我的课程
@login_required
@require_GET
def my_course(request):
    user = request.user
    if user.is_student:
        user = StudentProfile.objects.filter(user=user).first()
        print(user.classname)
        cour_teachs = CourseTeacher.objects.filter(classname=user.classname).all()
        print(cour_teachs)
        total_price = sum(course_teacher.textbook.price for course_teacher in cour_teachs)
        return render(request, 'mycourse.html', {'cour_teachs': cour_teachs, 'total_price': total_price})
    else:
        return HttpResponse("您不是学生")


def stulogout(request):
    logout(request)
    return redirect('/')


# 教师修改信息
@login_required
@require_http_methods(['GET', 'POST'])
def tea_change(request):
    if request.method == 'POST':
        phone = request.POST.get('phone')
        password = request.POST.get('password')
        teacher_profile = TeacherProfile.objects.filter(phone=phone).first()
        print(phone, password)
        if teacher_profile:
            user = teacher_profile.user
            # 密码校验通过，可以修改密码
            user.set_password(password)
            user.save()
            return HttpResponse("密码更新成功")
        else:
            return HttpResponse("修改失败！")
    else:
        return render(request, 'tea_change.html')


# 添加班级
@login_required
@require_http_methods(['GET', 'POST'])
def add_class(request):
    if request.method == 'POST':
        name = request.POST.get('name')
        if name == '':
            return render(request, 'add_class.html', {'msg': '班级名称不能为空！'})
        if ClassModel.objects.filter(name=name).exists():
            return render(request, 'add_class.html', {'msg': '该班级已存在！'})
        ClassModel.objects.create(name=name)
        return render(request, 'add_class.html', {'msg': '添加成功！'})
    else:
        return render(request, 'add_class.html')


# 添加课程
@login_required
@require_http_methods(['GET', 'POST'])
def add_course(request):
    if request.method == 'POST':
        name = request.POST.get('name')
        study_time = request.POST.get('study_time')
        if name == '' or study_time == '':
            return render(request, 'add_course.html', {'msg': '课程名称或学时不能为空！'})
        if CourseModel.objects.filter(name=name).exists():
            return render(request, 'add_course.html', {'msg': '该课程已存在！'})
        CourseModel.objects.create(name=name, study_time=study_time)
        return render(request, 'add_course.html', {'msg': '添加成功！'})
    else:
        return render(request, 'add_course.html')


# 添加教材
@login_required
@require_http_methods(['GET', 'POST'])
def add_textbook(request):
    if request.method == 'POST':
        name = request.POST.get('name')
        price = request.POST.get('price')
        if name == '' or price == '':
            return render(request, 'add_textbook.html', {'msg': '教材名称或价格不能为空！'})
        if TextbookModel.objects.filter(name=name).exists():
            return render(request, 'add_textbook.html', {'msg': '该教材已存在！'})
        TextbookModel.objects.create(name=name, price=price)
        return render(request, 'add_textbook.html', {'msg': '添加成功！'})
    else:
        return render(request, 'add_textbook.html')


# 学生管理
@login_required
@require_http_methods(['GET', 'POST'])
def add_students(request):
    if request.method == 'POST':
        data = request.POST.get('data')
        print(data)
        print(request.POST)
        class_id = request.POST.get('class_id')
        userid = request.POST.get('userid')
        if class_id == '' or userid == '':
            return render(request, 'add_students.html', {'msg': '班级或学生不能为空！'})
        student = StudentProfile.objects.get(user_id=userid)
        if not student:
            return render(request, 'add_students.html', {'msg': '该学生不存在！'})
        if not ClassModel.objects.filter(id=class_id).exists():
            return render(request, 'add_students.html', {'msg': '该班级不存在！'})
        if student.classname_id == class_id:
            return render(request, 'add_students.html', {'msg': '该学生已存在该班级！'})
        if student.classname_id:
            return render(request, 'add_students.html', {'msg': '该学生已存在其他班级！'})
        student.classname_id = class_id
        student.save()
        email=student.user.email
        # 发送邮件
        send_mail('加入班级通知', message=f'{student.user.username}同学您好，您已被添加到班级{ClassModel.objects.get(id=class_id).name}中，请登录系统查看。', recipient_list=[email],
              from_email=None)

        return render(request, 'add_students.html', {'msg': '添加成功！'})
    else:
        classes = ClassModel.objects.all()
        users = StudentProfile.objects.filter(classname=None)
        return render(request, 'add_students.html', {'classes': classes, 'users': users})


# 添加授课
@login_required
@require_http_methods(['GET', 'POST'])
def add_teach(request):
    if request.method == 'POST':
        print(request.POST)

        courseid = request.POST.get('courseid')
        teacherid = request.POST.get('teacherid')
        class_id = request.POST.get('class_id')
        textid = request.POST.get('textid')
        year = request.POST.get('year')
        semester = request.POST.get('semester')
        content = request.POST.get('content')
        # 校验是否为空
        if courseid == '' or teacherid == '' or class_id == '' or textid == '' or year == '' or semester == '' or content == '':
            return JsonResponse({'code': 402, 'msg': '信息不能为空！'})
        if CourseTeacher.objects.filter(course_id=courseid, classname_id=class_id,
                                        textbook_id=textid, school_year=year, semester=semester).exists():
            return JsonResponse({'code': 402, 'msg': '该授课已存在！'})
        try:
            course_teach = CourseTeacher.objects.create(course_id=courseid, teacher_id=teacherid, classname_id=class_id,
                                         textbook_id=textid, school_year=year, semester=semester, content=content)
            print("添加授课成功！")
            return JsonResponse({'code': 200, 'msg': '添加成功！', 'data':course_teach.id})
        except Exception as e:
            print(e)
            return JsonResponse({'code': 402, 'msg': '添加失败！'})
    else:
        courses = CourseModel.objects.all()
        teachers = TeacherProfile.objects.all()
        classes = ClassModel.objects.all()
        textbooks = TextbookModel.objects.all()
        return render(request, 'add_teach.html',
                      {'courses': courses, 'teachers': teachers, 'classes': classes, 'textbooks': textbooks})


@require_GET
def detail(request, id):
    try:
        course_teach = CourseTeacher.objects.get(id=id)
        return render(request, 'detail.html', {'course_teach': course_teach})
    except CourseTeacher.DoesNotExist:
        return render(request, 'detail.html', {'msg': '授课不存在！'})


@require_GET
def search(request):
    key = request.GET.get('key')
    # 从博客的标题和内容中搜索
    course_teachs = CourseTeacher.objects.filter(Q(course__name__contains=key) | Q(textbook__name__contains=key) | Q(content__contains=key)).all()
    print(course_teachs)
    return render(request, 'index.html', {'course_teachs': course_teachs})